<template>
  <!-- <lay-button type="primary" @click="changedialogVisible">填报信息</lay-button> -->
  <lay-layer v-model="dialogVisible" :title="dialogTitle" :area="['400px', '']" :close="handleClose" :btn="action">
    <div style="padding: 20px;">
      <lay-form :model="form" ref="formRef" :rules="rules">
        <lay-form-item label="名称" prop="name">
          <lay-input v-model="form.name"></lay-input>
        </lay-form-item>
        <lay-form-item label="单位" prop="unit">
          <lay-input v-model="form.unit"></lay-input>
        </lay-form-item>
        <lay-form-item label="数值" prop="value">
          <lay-input-number position="right" v-model="form.value"></lay-input-number>
        </lay-form-item>
        <lay-form-item label="描述" prop="remark">
          <lay-input v-model="form.remark"></lay-input>
        </lay-form-item>
        <lay-form-item label="数据来源" prop="source">
          <lay-textarea rows="3" v-model="form.source"></lay-textarea>
        </lay-form-item>
      </lay-form>
    </div>
  </lay-layer>
</template>

<script setup>
import { ref, reactive, defineProps, defineEmits } from 'vue'
import { layer } from '@layui/layui-vue'
import api from '@/api';

const emits = defineEmits(['update:modelValue', 'initDataList'])
const props = defineProps(
  {
    id: { type: Number, default: -1, required: true },
    dialogTitle: { type: String, default: '', required: true },
    dialogVisible: { type: Boolean, default: false, required: true }
  }
)
const form = ref({ id: -1, name: '', unit: '', value: '', source: '', remark: '' })
const formRef = ref(null)
const rules = ref({
  name: [
    { required: true, message: '请输入名称！' },
    { type: 'string', message: '名称须为字符串!', trigger: 'blur' }
  ],
  value: [
    { required: true, message: '请输入数值！' },
    // { type: 'number', message: '必须为数字', trigger: 'blur' },
  ]
})

const dialogVisible = ref(false);

const handleClose = () => {
  emits('update:modelValue', false)
  // treeId.value = null
}

const action = ref([
  {
    text: "确认",
    callback: () => {
      // Try several common validate API shapes: promise, boolean, or callback
      formRef.value.validate(async (valid) => {
        if (valid) {
          console.log("字段校验成功！")
          await api.post("price/save", form.value).then((res) => {
            if (res.code === 200) {
              layer.msg(res.msg, { icon: 1, time: 1000 });
              emits("initDataList")
              handleClose();
            } else {
              layer.msg(res.msg, { icon: 2, time: 1000 });
            }
          })
        } else {
          console.log("字段校验失败！")
        }
      })
    }
  },
  {
    text: "取消",
    callback: handleClose
  }
])
</script>